<?php


namespace App\Http\Controllers\Backend;



use App\Services\Business\Models\MediaImage;
use App\Services\Business\Models\MediaCategory;
use App\Services\Business\Models\MediaImageables;
use App\Services\Business\Models\Question;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\Company\ImageUploadRequest;
use App\Services\Business\Interfaces\MediaServiceInterface;
use App\Services\Business\Services\MediaService;


class MediaImageController extends BaseController
{


    /**
     * @var MediaService
     */
    protected $mediaService;

    public function __construct(

        MediaService      $mediaService
    )
    {

        $this->mediaService = $mediaService;
    }

    public function index(Request $request)
    {
        $keywords = $request->input('keywords');
        $cid = (int)$request->input('media_category_id');

        $images = MediaImage::query()
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($cid, function ($query) use ($cid) {
                $ids = [$cid];
                $childrenIds = MediaCategory::query()
                    ->where('parent_id', $cid)
                    ->select(['id'])
                    ->get()
                    ->pluck('id')
                    ->toArray();
                $ids = array_merge($ids, $childrenIds);
                $query->whereIn('category_id', $ids);
            })
            ->orderByDesc('id')
            ->paginate($request->input('size'));

        return $this->successData(compact('images'));
    }

    /**
     * @param ImageUploadRequest $request
     * @return JsonResponse
     */
    public function upload(ImageUploadRequest $request)
    {
        $file = $request->filldata();
        $prefix = 'media/' . date("Ymd");
        $data = save_image($file, $prefix);
        // 创建记录
        $image = MediaImage::create([
            'title' => $data['name'],
            'url' => $data['urlMedium'],
            'url_small' => $data['urlSmall'],
            'user_id' => Auth::id(),

        ]);

        return $this->successData(compact('image'));
    }


    /**
     * 素材图片的删除
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function delete(Request $request, $id)
    {

        $hasExists = $this->mediaService->hasImageRefer([$id]);
        if ($hasExists) {
            return $this->error(__('图片补引用,不能被删除'));
        }
        $image = MediaImage::query()->where('id', $id)->first();
        if ($image) {
            Storage::disk('oss')->delete([$image->path,$image->path_small]);
        }
        $image->delete();
        return $this->success();
    }

    /**
     * 批量删除
     * @param Request $request
     * @return JsonResponse
     */
    public function batchDelete(Request $request)
    {
        $ids = $request->input('ids');
        if ($this->mediaService->hasImageRefer($ids)) {
            return $this->error(__('被引用,不能删除'));
        }

        $query  = MediaImage::query()->whereIn('id', $ids);
        $images =   $query->get();
        $paths = $images->flatMap(function ($image) {
            return [$image->path, $image->path_small];
        })->all();
        //删除阿里云的素材文件
        Storage::disk('oss')->delete($paths);
        //素材本身
        $query->delete();
        return $this->success(__('删除图片成功'));
    }

    public function update(Request $request, $id)
    {

        MediaImage::find($id)->update(['title' => $request->input('title')]);
        return $this->success(__('图片更新成功'));
    }

//    替换文件
    public function replace(ImageUploadRequest $request, $id)
    {
        $file = $request->filldata();
        $prefix = 'media/' . date("Ymd");
        $data = save_image($file, $prefix);
        $from = (int)$request->input('from', 0);
        // 创建记录
        MediaImage::query()->where('id', $id)->update([
            'title' => $data['name'],
            'media_url' => $data['url'],
            'path' => $data['path'],

        ]);
        return $this->success(__('图片更新成功'));
    }

    public function remove(Request $request)
    {
        $categoryId = $request->input('category_id');
        $ids = $request->input('ids', []);
        MediaImage::query()->whereIn('id', $ids)->update(['category_id' => $categoryId]);
        return $this->success(__('批量移至文件夹成功'));
    }

    public function refer(Request $request)
    {

        $imageIds = $request->input('ids');
        if (!is_array($imageIds)) {
            $imageIds = [$imageIds];
        }
        $size = $request->input('size');
        $page = $request->input('page');

        ['list' => $list, 'total' => $total] = $this->mediaService->getReferImageResource($imageIds, $page, $size);

        return $this->successData(compact('list', 'total'));


    }


}
